package com.znsb.msfq.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @name： 图文使用
 * @author： 杨广
 * @phone： 17382373271
 * @createTime： 2017/2/9
 * @modifyTime： 2017/2/9
 * @explain：
 */

public class URLImageParser implements ImageGetter {
    private Activity context;
    private TextView container;
    private DisplayMetrics metrics;
    private Map<String, SoftReference<Drawable>> drawables;
    private Bitmap bitmap = null;

    public URLImageParser(TextView t, Activity context) {
        this.container = t;
        this.context = context;
        metrics = new DisplayMetrics();
        drawables = new HashMap<String, SoftReference<Drawable>>();
        ((Activity) this.context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
    }

    @Override
    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = null;
        Drawable d = null;
        SoftReference<Drawable> softD = drawables.get(source);
        if (softD != null) {
            d = softD.get();
        }

        if (d == null) {
            if (source.startsWith("http") || source.endsWith("gif") || source.endsWith("png")
                    || source.endsWith("jpg")) {
                urlDrawable = new URLDrawable();
                ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask(urlDrawable, source);
                asyncTask.execute();
                return urlDrawable;
            }
        }
        return d;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {

        private URLDrawable mURLDrawable;
        private String urlString;

        public ImageGetterAsyncTask(URLDrawable uDrawable, String urlString) {
            this.mURLDrawable = uDrawable;
            this.urlString = urlString;
        }

        @Override
        protected void onPostExecute(Drawable result) {
            if (result != null) {
                // it's important to call setBounds otherwise the image will
                // have recyler_divider size of 0px * 0px and won't show at all
                drawables.put(urlString, new SoftReference<Drawable>(result));
                this.mURLDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(),
                        0 + result.getIntrinsicHeight());
                this.mURLDrawable.drawable = result;
                URLImageParser.this.container.invalidate();

                LayoutParams relLp = (LayoutParams) URLImageParser.this.container
                        .getLayoutParams();
                relLp.width = LayoutParams.MATCH_PARENT;
                URLImageParser.this.container.setLayoutParams(relLp);
                URLImageParser.this.container.setEllipsize(null);
                CharSequence strContent = URLImageParser.this.container.getText();
                if (strContent instanceof Spanned) {
                    URLImageParser.this.container.setText((Spanned) strContent);
                }
            }
        }

        @Override
        protected Drawable doInBackground(String... params) {
            if (!urlString.startsWith("http")) {
                if (urlString.startsWith("//")) {
                    urlString = "http" + urlString;
                } else {
                    urlString = "http://" + urlString;
                }
            }
            return fetchDrawable(urlString);
        }

        // 获取URL的Drawable对象
        public Drawable fetchDrawable(String urlString) {
            BitmapDrawable bitmapDrawable = null;

            try {
                URL url = new URL(urlString);
                int bitmapWidth = metrics.widthPixels * 8 / 10;
                //                Bitmap bitmap = LazyImageLoader.getInstance(context).getImgFromLocal(url,
                //                        bitmapWidth, bitmapWidth);


                try {
                    bitmap = Picasso.with(context).load(urlString).get();
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                if (bitmap == null) {
                    //                    bitmap = LazyImageLoader.getInstance(context).getBitmapFromWeb(url,
                    //                            bitmapWidth, bitmapWidth);
                }
                if (bitmap != null) {
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    float scale = 1;
                    if (width > metrics.widthPixels) {
                        scale = metrics.widthPixels / width;
                        Matrix m = new Matrix();
                        m.postScale(scale, scale);
                        m.reset();
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
                    }
                    width = bitmap.getWidth();
                    height = bitmap.getHeight();
                    if (width > 100 && height > 100) {
                        //主要过滤小图，例如表情等，不进行放大处理
                        scale = (metrics.widthPixels * 8f / 10) / width;
                        Matrix matrix = new Matrix();
                        matrix.postScale(scale, scale); //长和宽放大缩小的比例
                        try {
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                        } catch (OutOfMemoryError e) {

                        }
                        matrix.reset();
                    }

                    bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
                    bitmapDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                }
            } catch (MalformedURLException e) {
            }
            return bitmapDrawable;
        }
    }

    public class URLDrawable extends BitmapDrawable {
        protected Drawable drawable;

        @Override
        public void draw(Canvas canvas) {
            if (drawable != null) {
                drawable.draw(canvas);
            }
        }
    }
}
